<template>
    <!-- 区域巡检项 -->
    <div class="layout-padding">
      <basic-container
      class="layout-padding-auto layout-padding-view">
        <avue-crud
            v-model='form'
            ref='crud'
            :page='page'
            :data='data'
            :table-loading='tableLoading'
            :permission='permissionList'
            :option='tableOption'
            :before-open='handleOpenBefore'
            :span-method='spanMethod'
            @on-load='getList'
            @search-change='searchChange'
            @refresh-change='refreshChange'
            @size-change='sizeChange'
            @current-change='currentChange'
            @row-del='rowDel'
            @row-update='handleUpdate'
            @selection-change='selectionChange'
        >
          <template #menu-left>
            <!-- <el-button v-if='permissions.om_inspection_area_items_add' type='primary' @click='handleAdd'> -->
            <el-button type='primary' @click='handleAdd'>
              <el-icon style='margin-right: 6px;'>
                <Plus/>
              </el-icon>
              新增
            </el-button>
            <!-- v-if='permissions.om_inspection_area_items_del' -->
            <el-button
                
                class='filter-item'
                plain
                type='primary'
                icon='el-icon-delete'
                @click='plDelete'
            >
              批量删除
            </el-button>
          </template>
        </avue-crud>
      </basic-container
      >
      <adddialog ref='adddialog' @refreshList='refreshList'/>
    </div>
  </template>
  
  <script>
  import adddialog from './adddialog.vue'
  import {tableOption} from '/@/const/crud/check/omicheckregion'
  import {getlistData, setList, delList, delAllObj, getAdminTree} from '/@/api/check/omicheckregion'
  import {mapGetters} from 'vuex'
  import {ElLoading} from "element-plus";
  
  export default {
    name: 'omicheckregion',
    components: {adddialog},
    data() {
      return {
        data: [],
        tableOption: tableOption,
        spanArr: [
          {
            prop: 'regionFacilityName',
            span: []
          },
          {
            prop: 'departmentName',
            span: []
          },
        ],
        form: {},
        tableLoading: false,
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        loading: null,
        adminList: {},
      }
    },
    mounted() {
      this.getAdminTree()
    },
    watch: {
      'form.departmentName'(newValue) {
        if (newValue) {
          this.form.departmentId = this.queryTree(this.adminList, newValue)
        }
      }
    },
    computed: {
    //   ...mapGetters(['permissions']),
      permissionList() {
        return {
        //   getBtn: this.validData(this.permissions.om_inspection_area_items_get, false),
        //   addBtn: this.validData(this.permissions.om_inspection_area_items_add, false),
        //   editBtn: this.validData(this.permissions.om_inspection_area_items_edit, false),
        //   delBtn: this.validData(this.permissions.om_inspection_area_items_del, false)
        }
      }
    },
    methods: {
      queryTree(tree, value) {
        let stark = [];
        stark = stark.concat(tree);
        while (stark.length) {
          const temp = stark.shift();
          if (temp.children) {
            stark = stark.concat(temp.children);
          }
          if (temp.name === value) {
            return temp.id;
          }
        }
        return "";
      },
      getAdminTree() {
        getAdminTree().then((res) => {
          this.adminList = res.data[0]
        })
      },
      openLoading() {
        this.loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
      },
      closeLoading() {
        this.loading.close()
      },
      // 新增刷新页面
      refreshList() {
        this.getList(this.page)
      },
      // 打开新增弹出框
      handleAdd() {
        this.$refs.adddialog.dialogFormVisible = true
      },
      // 全选按钮
      selectionChange(list) {
        this.selectList = list
      },
      // 删除
      rowDel: function (row, index) {
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(function () {
              return delList({id: row.id, regionCode: row.regionCode, regionFacilityCode: row.regionFacilityCode})
            })
            .then((data) => {
              this.$message.success('删除成功')
              this.getList(this.page)
            })
            .catch((cancelorerror) => {
            })
      },
      // 修改更新数据
      handleUpdate: function (row, index, done, loading) {
        setList(row)
            .then((data) => {
              this.$message.success('修改成功')
              done()
              this.getList(this.page)
            })
            .catch(() => {
              loading()
            })
      },
      // 获取表格数据
      getList(page, params) {
        this.data = []
        this.tableLoading = true
        getlistData(
            Object.assign(
                {
                  current: page.currentPage,
                  size: page.pageSize
                },
                params,
                this.searchForm
            )
        )
            .then((response) => {
              this.data = response.data.records
              this.page.total = response.data.total
              this.tableLoading = false
              this.rowSort()
              this.rowCalc()
            })
            .catch(() => {
              this.tableLoading = false
            })
  
      },
      // 分页大小
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 改变页数
      currentChange(current) {
        this.page.currentPage = current
      },
      // 点击搜索
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新表格
      refreshChange() {
        this.getList(this.page)
      },
      // 打开前回调
      handleOpenBefore(show, type) {
        show()
      },
      //批量删除
      plDelete() {
        if (this.selectList.length > 0) {
          this.$confirm('是否确认删除以选择的数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
              .then(() => {
                let ids = []
                this.selectList.forEach((data) => {
                  ids.push({pid: data.regionCode, id: data.id, child: data.regionFacilityCode})
                })
                this.openLoading()
                return delAllObj(ids).then((res) => {
                  this.closeLoading()
                  this.$message.success('删除成功')
                  this.getList(this.page)
                }).catch(() => {
                  this.closeLoading()
                  this.$message.error('删除失败')
                  this.getList(this.page)
                })
              })
              .then((data) => {
  
              })
              .catch((cancelorerror) => {
              })
        }
      },
      // 合并列行
      rowCalc() {
        this.spanArr.forEach((ele, index) => {
          let parent
          if (index !== 0) parent = this.spanArr[ele.parent || index - 1].span
          ele.span = this.rowSpan(ele.prop, parent)
        })
      },
      rowSort(list) {
        let propList = this.spanArr.map(ele => ele.prop)
        this.spanArr.forEach((ele, index) => {
          let key = ele.prop
          this.data = this.data.sort((a, b) => {
            let flag = true
            for (let i = 0; i < index; i++) {
              let prop = this.spanArr[i].prop
              flag = flag && a[prop] == b[prop]
            }
            if (flag) {
              if (a[key] < b[key]) {
                return 1
              } else if (a[key] > b[key]) {
                return -1
              }
              return 0
            }
            return 0
          })
        })
      },
      rowSpan(key, parent) {
        let list = []
        let position = 0
        this.data.forEach((item, index) => {
          if (index === 0) {
            list.push(1)
            let position = 0
          } else {
            if (this.data[index][key] === this.data[index - 1][key]) {
              if (parent && parent[index] !== 0) {
                list.push(1)
                position = index
              } else {
                list[position] += 1
                list.push(0)
              }
            } else {
              list.push(1)
              position = index
            }
          }
        })
        return list
      },
      spanMethod({row, column, rowIndex, columnIndex}) {
        for (let i = 0; i < this.spanArr.length; i++) {
          const ele = this.spanArr[i]
          if (column.property == ele.prop) {
            const _row = ele.span[rowIndex]
            const _col = _row > 0 ? 1 : 0
            return {
              rowspan: _row,
              colspan: _col
            }
          }
        }
      }
    }
  }
  </script>
  
  <style lang='scss'>
  </style>